<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\general\LihuaCity;
use app\common\model\LihuaArticles; //宣传文章模型
use app\common\model\LihuaUserbonus;
use app\common\model\LihuaBonusAct;
use app\common\model\LihuaBonusActlog;
use app\common\model\User;
use app\common\model\LihuaBonus;
use app\common\model\LihuaMainPopup;

/**
 * 活动文章主页
 */
class Articles extends Api
{
    protected $noNeedLogin = ['detail', 'sendbonus', 'loginsendbonus', 'check_have_get'];
    protected $noNeedRight = ['*'];

    /**
     * 活动文章主页
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="store_id", type="int", required=true, description="门店ID")
     * @ApiParams   (name="goods_nums", type="string", required=true, description="商品ID及数量键值对JSON字符串")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1573029605","data":{"goods":[{"id":43,"category_id":57,"name":"蛋花汤料","short_name":"蛋花汤","description":"含汤碗 净含量8克（配餐产品，不单独售卖）","pic":"http://image.lihua.com/images/newweb/2016/09/thumb_57cfc743835e0.jpg","price":2,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":0,"enable_stock":0,"num":3,"num_price":6},{"id":44,"category_id":57,"name":"三件套","short_name":"三件套","description":"三件套（不含汤勺，配餐产品，不单独售卖）","pic":"http://image.lihua.com/images/newweb/2018/12/thumb_5c0f521445dd8.JPG","price":2.5,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":0,"enable_stock":0,"num":1,"num_price":2.5}],"goods_nums":{"43":3,"44":1},"goods_stocks":null,"goods_amount":8.5,"packing_fee":0,"enough_fee":0,"subtotal":8.5,"discount":0,"submit":0,"error":"请选择一份主食，配餐商品单点不送"}})
     */
    public function index()
    {
        $this->request->filter('trim,strip_tags');
        $city_id    = (int)$this->request->post('city_id', 0);
        $store_id   = (int)$this->request->post('store_id', 0);
        if (!$city_id || !$store_id) $this->error('非法操作');

        $city = LihuaCity::getCityInfo($city_id);
        if (!$city) $this->error('非法操作');

        $goods_nums = $this->request->post('goods_nums', '');
        if ($goods_nums) {
            $goods_nums = json_decode($goods_nums, true);
            if (json_last_error()) $this->error('非法操作');
        } else {
            $goods_nums = [];
        }

        $data = LihuaGoods::getCartGoodsList($store_id, $goods_nums);
        //城市满减
        $enough = LihuaCity::countEnough($city['enough'], $data['goods_amount']);

        $actfree = [
            'half'          => [], //第二份半价
            'sales'         => [], //促销商品
            'half_free'     => 0,  //第二份半价优惠费用
            'sales_free'    => 0,  //促销商品优惠会用
            'half_mutex'    => 0,  //半价活动是否互斥
            'sales_mutex'   => 0,  //半价活动是否互斥
            'enough_reduce' => 0,  //满减优惠金额
        ];

        //计算城市活动优惠
        if ($this->token) {
            $user_id  = $this->auth->id;
            $actfree = LihuaActivity::computingOffers($city_id, $data, $user_id, 1, 1, $store_id);
            if( $actfree['half_free']>0 || $actfree['sales_free']>0 ) { //如果第二份半价和促销商品有优惠则不能使用满减优惠
                if($actfree['half_mutex']==1 && $actfree['half_free']>0){ //活动互斥的情况下才会将满减的优惠删除
                    $enough['reduce'] = 0;
                }
                if($actfree['sales_mutex']==1 && $actfree['sales_free']>0){ //活动互斥的情况下才会将满减的优惠删除
                    $enough['reduce'] = 0;
                }
            }
        }
        $actfree['enough_reduce'] = (int)$enough['reduce'];
        $discount = round($actfree['half_free'] + $actfree['sales_free'] + $enough['reduce'], 2);//已优惠
        $subtotal = round($data['goods_amount'] - $discount, 2);//小计
        $data['enough_fee'] = $enough['reduce'];
        $data['subtotal'] = $subtotal;
        $data['discount'] = $discount;

        //结算
        if (!$data['alone_sale']) {
            $submit = 0;
            $error  = '请选择一份主食，配餐商品单点不送';
        } elseif ($data['lack_goods']['ids']) {
            $submit = 0;
            $error  = join('、', $data['lack_goods']['names']) . ' 库存不足';
        } elseif ($data['goods_amount'] < $city['min_price']) {
            $submit = 0;
            $error  = '商品起送价￥' . $city['min_price'];
        } else {
            $submit = 1;//为1可提交结算
            $error  = '';
        }

        $data['actinfo'] = $actfree;
        $data['submit'] = $submit;
        $data['error']  = $error;
        
        // unset($data['alone_sale'], $data['lack_goods']);
        $this->success('OK', $data);
    }

    /**
     * 文章详情
     * */
    public function detail()
    {
        $id = (int)$this->request->post('id', 0);
        if (!$id) $this->error('非法操作');
        $res = LihuaArticles::where('id', $id)->find();
        if($res){
            $this->success('OK', $res);
        }else{
            $this->error('内容不存在');
        }
    }

    //判断活动是否已经参加过了
    public function check_have_get(){
        $article_id = (int)$this->request->post('article_id', 0); //文章id
        $uid = (int)$this->request->post('uid', 0); //用户id
        $platform = $this->request->post('platform', ""); //平台类型 app xcx
        if (!$article_id || !$uid || !$platform) $this->error('非法操作');
        $res = LihuaArticles::where('id', $article_id)->find();
        if($res){
            //获取红包活动
            $open_status = 0;
            $share_status = 0;
            $open_active = LihuaBonusAct::where('id', $res['open_active_id'])->find();
            $share_active = LihuaBonusAct::where('id', $res['share_active_id'])->find();
            $LihuaBonusAct_res_share = LihuaBonusActlog::where(['act_id' => $res['share_active_id'], 'user_id'=>$uid, 'type' => 1])->find();
            $LihuaBonusAct_res_open = LihuaBonusActlog::where(['act_id' => $res['open_active_id'], 'user_id'=>$uid, 'type' => 0])->find();
            if(!!$LihuaBonusAct_res_open) $open_status = 1; 
            if(!!$LihuaBonusAct_res_share) $share_status = 1; 
            $this->success('OK', [
                "open_status" => $open_status,
                "share_status" => $share_status,
            ]);
        }else{
            $this->error('内容不存在');
        }


        
    }

    /*登录获取红包*/
    public function loginsendbonus()
    {
        $id = (int)$this->request->request('id', 0); //活动id
        $uid = (int)$this->request->request('uid', 0); //用户id
        $platform = $this->request->request('platform', ""); //平台类型 app xcx

        if (!$id) $this->error('非法操作');
        if (!$uid) $this->error('请先登录后操作');
        $act = LihuaMainPopup::where('id', $id)->find();
        if($act){
            //获取红包活动
            $bonus_act = LihuaBonusAct::where('id', $act['active_id'])->find();
            //获取红包参数
            $act_arr = json_decode($bonus_act['bonus_config']);
            $success_pic = ''; //成功后的谈框图片
            $act_status = 0; //打开动作参与活动0未参加，1表示参加中，2表示已经参加过，3表示每天可以领取
            $LihuaBonusAct_res = LihuaBonusActlog::where(['act_id' => $act['active_id'], 'user_id'=>$uid, 'type' => 2])->find();
            if(!!$act['everyday']) {
                $LihuaBonusAct_res = false;
            }
            if(!!$LihuaBonusAct_res){ 
                $act_status = 2; 
            }else{
                /**
                 * 登录红包分为随机红包和指定红包
                 * **/
                //配置为0 的情况下是发放指定红包
                if($bonus_act['bonus_type']==0){
                    /**
                     * 打开动作
                     **/
                    if(!$LihuaBonusAct_res){
                        $open_bonus_id_arr = [];
                        $open_bonus_map = [];
                        foreach ($act_arr as $k => $v) {
                            $open_bonus_id_arr[] = $v->bonus_id;
                            $open_bonus_map[$v->bonus_id] = $v->num;
                        }
                        //获取红包详情
                        $open_bonus_list = LihuaBonus::where(['id'=>['in', $open_bonus_id_arr]])->select();
                        $havesend = 0;
                        foreach ($open_bonus_list as $k => $v) {
                            $start_date_s = date('Y-m-d');
                            $end_date_s = date('Y-m-d', strtotime('+'.$v['days'].' day'));
                            $s = [
                                "user_id" => $uid,
                                "city_id" => $v['city_id'],
                                "bonus_id" => $v['id'],
                                "num" => $open_bonus_map[$v['id']],
                                "name" => $v['name'],
                                "type" => $v['type'],
                                "reach" => $v['reach'],
                                "reduce" => $v['reduce'],
                                "des" => $bonus_act['name'],
                                "start_date" => $start_date_s,
                                "end_date" => $end_date_s,
                                "order_sn" => '',
                                "goods" => $v['goods'],
                            ];
                            $ress = LihuaUserbonus::sendUserBonus($s);
                            if(!!$ress) $havesend += 1;
                        }
                        //在发送红包成功的基础上，生成发送记录
                        if($havesend > 0){
                            LihuaBonusActlog::createlog([
                                "user_id" => $uid,
                                "act_id" => $act['active_id'],
                                "act_name" => $bonus_act['name'],
                                "type" => 2,
                                "platform" => $platform,
                            ]);
                            $success_pic = $bonus_act['pic_success'];
                            $act_status = 1;
                        }
                    }
                }

                //配置为1 的情况下发放随机红包
                if($bonus_act['bonus_type']==1){
                    $act_info = $act_arr[0];
                    $act_bonus = explode(',', $act_info->bonus_arr); //随机红包配置
                    $act_bonus_num = (int)$act_info->num; //随机数量
	                $i = mt_rand(0, count($act_bonus)-1);
	                $money = $act_bonus[$i];
	                $start_date_s = date('Y-m-d');
                    $end_date_s = date('Y-m-d', strtotime('+30 day'));
                    $havesend = 0;
                    for ($x=0; $x<$act_bonus_num; $x++) {
                        $s = [
                            "user_id" => $uid,
                            "city_id" => $bonus_act['city_id'],
                            "bonus_id" => 0,
                            "num" => 1,
                            "name" => $bonus_act['name'],
                            "type" => 3,
                            "reach" => 0,
                            "reduce" => $money,
                            "des" => $bonus_act['name'],
                            "start_date" => $start_date_s,
                            "end_date" => $end_date_s,
                            "order_sn" => '',
                            "goods" => '',
                        ];
                        $ress = LihuaUserbonus::sendUserBonus($s);
                        if(!!$ress) {
                            $havesend += 1;
                            LihuaBonusActlog::createlog([
                                "user_id" => $uid,
                                "act_id" => $act['active_id'],
                                "act_name" => $bonus_act['name'],
                                "type" => 2,
                                "platform" => $platform,
                            ]);
                            $success_pic = $bonus_act['pic_success'];
                            $act_status = 1;
                        }
                    }
                }
            }
            $this->success('OK', [
                'success_pic'=> $success_pic,
                'act_status' => $act_status,
            ]);
        }else{
            $this->error('内容不存在');
        }
    }

    /*文章宣传获取红包*/
    public function sendbonus()
    {
        $id = (int)$this->request->post('id', 0); //文章id
        $uid = (int)$this->request->post('uid', 0); //用户id
        $type = $this->request->post('type', 0); //类型 open share  // 分享动作 和 打开动作
        $platform = $this->request->post('platform', ""); //平台类型 app xcx

        if (!$id) $this->error('非法操作');
        if (!$uid) $this->error('请先登录后操作');
        $res = LihuaArticles::where('id', $id)->find();
        $today = date('Y-m-d');
        if($res){
            //获取红包活动
            $open_active = LihuaBonusAct::where('id', $res['open_active_id'])->find();
            $share_active = LihuaBonusAct::where('id', $res['share_active_id'])->find();
            $button_active = LihuaBonusAct::where('id', $res['button_active_id'])->find();
            //获取红包参数
            $open_act_arr = json_decode($open_active['bonus_config']);
            $share_act_arr = json_decode($share_active['bonus_config']);
            $button_act_arr = json_decode($button_active['bonus_config']);
            $success_pic = ''; //成功后的谈框图片
            $open_status = 0; //打开动作参与活动0未参加，1表示参加中，2表示已经参加过
            $share_status = 0; //分享动作参与活动0未参加，1表示参加中，2表示已经参加过
            $button_status = 0; //点击按钮参与活动0未参加，1表示参加中，2表示已经参加过

            $where_share = ['act_id' => $res['share_active_id'], 'user_id'=>$uid, 'type' => 1];
            $where_open = ['act_id' => $res['open_active_id'], 'user_id'=>$uid, 'type' => 0];
            $where_button = ['act_id' => $res['button_active_id'], 'user_id'=>$uid, 'type' => 3];
            if($res['everyday']==1){
                $where_share['createtime_text'] = ['like', '%'.$today.'%']; 
                $where_open['createtime_text'] = ['like', '%'.$today.'%']; 
                $where_button['createtime_text'] = ['like', '%'.$today.'%']; 
            }
            $LihuaBonusAct_res_share = LihuaBonusActlog::where($where_share)->find();
            $LihuaBonusAct_res_open = LihuaBonusActlog::where($where_open)->find();
            $LihuaBonusAct_res_button = LihuaBonusActlog::where($where_button)->find();
            $s = LihuaBonusActlog::getLastSql();
            if(!!$LihuaBonusAct_res_open){ $open_status = 2; }
            if(!!$LihuaBonusAct_res_share){ $share_status = 2; }
            if(!!$LihuaBonusAct_res_button){ $button_status = 2; }
            //打开动作
            if($type==0){
                //判断是否已经享受过活动了
                if(!$LihuaBonusAct_res_open){
                    $open_bonus_id_arr = [];
                    $open_bonus_map = [];
                    foreach ($open_act_arr as $k => $v) {
                        $open_bonus_id_arr[] = $v->bonus_id;
                        $open_bonus_map[$v->bonus_id] = $v->num;
                    }
                    //获取红包详情
                    $open_bonus_list = LihuaBonus::where(['id'=>['in', $open_bonus_id_arr]])->select();
                    $havesend = 0;
                    foreach ($open_bonus_list as $k => $v) {
                        $start_date_s = date('Y-m-d');
                        $end_date_s = date('Y-m-d', strtotime('+'.$v['days'].' day'));
                        $s = [
                            "user_id" => $uid,
                            "city_id" => $v['city_id'],
                            "bonus_id" => $v['id'],
                            "num" => $open_bonus_map[$v['id']],
                            "name" => $v['name'],
                            "type" => $v['type'],
                            "reach" => $v['reach'],
                            "reduce" => $v['reduce'],
                            "des" => $open_active['name'],
                            "start_date" => $start_date_s,
                            "end_date" => $end_date_s,
                            "order_sn" => '',
                            "goods" => $v['goods'],
                        ];
                        $ress = LihuaUserbonus::sendUserBonus($s);
                        if(!!$ress) $havesend += 1;
                    }
                    //在发送红包成功的基础上，生成发送记录 
                    if($havesend > 0){
                        LihuaBonusActlog::createlog([
                            "user_id" => $uid,
                            "act_id" => $res['open_active_id'],
                            "act_name" => $open_active['name'],
                            "type" => 0,
                            "platform" => $platform,
                        ]);
                        $success_pic = $open_active['pic_success'];
                        $open_status = 1;
                    }
                }else{
                    $this->error("您已参加过活动");
                }
            }
            if($type==1){
                //分享动作
                //判断是否已经享受过活动了
                if(!$LihuaBonusAct_res_share){
                    $share_bonus_id_arr = [];
                    $share_bonus_map = [];
                    foreach ($share_act_arr as $k => $v) {
                        $share_bonus_id_arr[] = $v->bonus_id;
                        $share_bonus_map[$v->bonus_id] = $v->num;
                    }
                    $share_bonus_list = LihuaBonus::where(['id'=>['in', $share_bonus_id_arr]])->select();
                    $havesend = 0;
                    foreach ($share_bonus_list as $k => $v) {
                        $s = [
                            "user_id" => $uid,
                            "city_id" => $v['city_id'],
                            "bonus_id" => $v['id'],
                            "num" => $share_bonus_map[$v['id']],
                            "name" => $v['name'],
                            "type" => $v['type'],
                            "reach" => $v['reach'],
                            "reduce" => $v['reduce'],
                            "des" => $share_active['name'],
                            "start_date" => $share_active['starttime_text'],
                            "end_date" => $share_active['endtime_text'],
                            "order_sn" => '',
                            "goods" => $v['goods'],
                        ];
                        $ress = LihuaUserbonus::sendUserBonus($s);
                        if(!!$ress) $havesend += 1;
                    }
                    //在发送红包成功的基础上，生成发送记录
                    if($havesend > 0){
                        LihuaBonusActlog::createlog([
                            "user_id" => $uid,
                            "act_id" => $res['share_active_id'],
                            "act_name" => $share_active['name'],
                            "type" => 1,
                            "platform" => $platform,
                        ]);
                        $success_pic = $share_active['pic_success'];
                        $share_status = 1;
                    }
                }else{
                    $this->error("您已参加过活动");
                }
            }
            if($type==3){
                //点击按钮事件
                //判断是否已经享受过活动了
                if(!$LihuaBonusAct_res_button){
                    $button_bonus_id_arr = [];
                    $button_bonus_map = [];
                    foreach ($button_act_arr as $k => $v) {
                        $button_bonus_id_arr[] = $v->bonus_id;
                        $button_bonus_map[$v->bonus_id] = $v->num;
                    }
                    $button_bonus_list = LihuaBonus::where(['id'=>['in', $button_bonus_id_arr]])->select();
                    $havesend = 0;
                    foreach ($button_bonus_list as $k => $v) {
                        $s = [
                            "user_id" => $uid,
                            "city_id" => $v['city_id'],
                            "bonus_id" => $v['id'],
                            "num" => $button_bonus_map[$v['id']],
                            "name" => $v['name'],
                            "type" => $v['type'],
                            "reach" => $v['reach'],
                            "reduce" => $v['reduce'],
                            "des" => $button_active['name'],
                            "start_date" => $button_active['starttime_text'],
                            "end_date" => $button_active['endtime_text'],
                            "order_sn" => '',
                            "goods" => $v['goods'],
                        ];
                        $ress = LihuaUserbonus::sendUserBonus($s);
                        if(!!$ress) $havesend += 1;
                    }
                    //在发送红包成功的基础上，生成发送记录
                    if($havesend > 0){
                        LihuaBonusActlog::createlog([
                            "user_id" => $uid,
                            "act_id" => $res['button_active_id'],
                            "act_name" => $button_active['name'],
                            "type" => 3,
                            "platform" => $platform,
                        ]);
                        $success_pic = $button_active['pic_success'];
                        $share_status = 1;
                    }
                }else{
                    $this->error("您已参加过活动");
                }
            }
            $this->success('OK', [
                'success_pic'=> $success_pic,
                'share_status' => $share_status,
                'open_status' => $open_status,
            ]);
        }else{
            $this->error('内容不存在');
        }
    }
  
}
